import {Button, Card, Cascader, Form, Input, message, Upload} from "antd";
import {ArrowLeftOutlined} from "@ant-design/icons";
import LinkButton from "../../components/link-button";
import TextArea from "antd/es/input/TextArea";
import {reqAddOrUpdateProduct, reqCategories} from "../../apis";
import {useEffect, useRef, useState} from "react";
import {useLocation, useNavigate} from "react-router-dom";
import PictureWall from "./picture-wall";
import RichTextEditor from "./rich-text-editor";

const Item = Form.Item;
const ProductAddUpdate = () => {
    const navigate = useNavigate()
    const location = useLocation()
    // 取出传递商品对象信息 如果没有是空对象
    const product = location.state?.product || {}
    console.log('路由传递商品参数',product)
    let isUpdate
    if(location.state){
        // console.log('路由传递参数1',location.state.product)
         isUpdate = !!location.state.product
        // console.log('location.state1',isUpdate)
    }else{
        isUpdate = false
    }

    const title = (
        <span>
           <LinkButton onClick={() => navigate('/product')}>
               <ArrowLeftOutlined/>
                <span style={{marginLeft: 10}}>{isUpdate ? '修改' : '添加'}商品</span>
           </LinkButton>
        </span>
    )
    // Item 样式布局
    const formItemsLayout = {
        labelCol: {span: 2},
        wrapperCol: {span: 8}
    }

    const editorRef = useRef(null)
    const submit = async(values) => {
        console.log('触发提交',values)
        console.log('搜集的detail',editorRef)
        // 1. 收集数据, 并封装成product对象
        let {name,desc,price,category} = values
        const myProduct = {
            name,
            desc,
            price,
            pCategoryId: '0',
            categoryId: category[0]
        }
        // 如果是更新, 需要添加_id
        if(isUpdate){
            myProduct._id = product._id
        }
        // 2. 调用接口请求函数去添加/更新
        const res = await reqAddOrUpdateProduct(myProduct)
        console.log('添加/更新商品结果',res)
        // 3. 根据结果提示
        if(res.status === 0){
            // if(isUpdate){
            //     message.success('更新商品成功')
            // }else{
            //     message.success('添加商品成功')
            // }

            message.success(`${isUpdate ? '更新商品成功' : '添加商品成功'}`)
            navigate('/product')
        }else{
            message.error(res.msg)
        }
    }

    const validatePrice = (rule,value,callback) => {
        // 验证通过
        if(value * 1 > 0){
            callback()
        }else{
            callback('price has to be greater than 0')
        }
    }

    const onChange = (value) => {
        console.log('触发onChange',value);
    };

    // const loadData = async (selectedOptions) => {
    //     // 得到选择的option对象
    //     const targetOption = selectedOptions[0]
    //     // 显示loading
    //     targetOption.loading = true
    //
    //     console.log('触发loadData',targetOption)
    //     const subCategory = await getCategoryList(targetOption.value)
    //     // 隐藏loading
    //     targetOption.loading = false
    //     if(subCategory &&  subCategory.length > 0){
    //         // 生成一个二级列表的options
    //         const childOptions = subCategory.map(c => ({
    //             value: c._id,
    //             label: c.name,
    //             isLeaf: true
    //         }))
    //         // 关联到当前option上
    //         targetOption.children = childOptions
    //     }else{
    //         // 当前选择分类无二级分类
    //         targetOption.isLeaf = true
    //     }
    //
    //     setCategoryList(categoryList)
    // };

    // 设置分类列表初始值
    const [categoryList, setCategoryList] = useState([])

    const initOptions = (category) => {
        // 整理数据格式
        const categoryList = category.map(c => ({
            value: c._id,
            label: c.name,
        }))

        console.log('整理好的列表',categoryList)
        setCategoryList(categoryList)
    }
    // 获取分类列表接口
    const getCategoryList = async (parentId) => {
        // 调取获取分类列表接口
        const res = await reqCategories(parentId)
        if( res.status === 0 ){
            const categorys = res.data
                // 一级分类列表
                initOptions(categorys)
        }


        // console.log('获取到的分类列表',res.data)
    }



    useEffect(() => {
        console.log('ref',editorRef)
        getCategoryList(0)
    }, []);
    // Product添加或更新路由界面
    return (
        <Card title={title}>
            <Form {...formItemsLayout}
                  onFinish={submit}
                  validateTrigger="onSubmit"
            >
                {/*要同时给Item添加 name  label  rules 才会出现红点校验*/}
                <Item label='商品名称'
                      name='name'
                      initialValue ={product.name}
                      rules={[{ required: true, message: 'Please input your product-name!' }]}>
                    <Input placeholder={"请输入商品名称"}></Input>
                </Item>
                <Item label='商品描述'
                      name='desc'
                      initialValue={product.desc}
                      rules={[{ required: true, message: 'Please input your product-desc!' }]}
                >
                    <TextArea placeholder={"请输入商品描述"}>
                    </TextArea>
                </Item>
                <Item label='商品价格'
                      name='price'
                      initialValue={product.price}
                      rules={[{ required: true,
                          validator: validatePrice
                      }]}
                >
                    <Input type={'number'} placeholder={"请输入商品价格"}
                        addonAfter={"元"}
                    ></Input>
                </Item>
                <Item label='商品分类'
                      name='category'
                      initialValue={[product.categoryId]}
                      rules={[{ required: true, message: 'Please input your product-category!' }]}
                >
                    <Cascader
                        initialvalue={['']}
                        options={categoryList}
                        // loadData={loadData}
                        onChange={onChange}
                    ></Cascader>
                </Item>
                <Item label={'商品图片'}
                      name='imgs'
                >
                    <PictureWall imgs={product.imgs}></PictureWall>
                </Item>
                <Item label='商品详情'
                      name='detail'
                      labelCol={{span: 2}}
                      wrapperCol={{span: 20}}>
                    <RichTextEditor editorRef={editorRef} />
                </Item>

                <Item>
                    {/*设置htmlType = 'submit' onFinish接收值 */}
                    <Button type="primary"  htmlType="submit">提交</Button>
                </Item>
            </Form>
        </Card>
    )
}
export default ProductAddUpdate;
